import express from "express";
import cors from "cors";
import helmet from "helmet";
import morgan from "morgan";
import { WebSocket, WebSocketServer } from "ws";
import * as dotenv from "dotenv";
import { createPool } from "./config/database";

// 导入路由
import apiRoutes from "./routes/api";

// 加载环境变量
dotenv.config();

const app = express();
const PORT = process.env.PORT || 8089;

// 类型定义
interface EmergencyEvent {
  type: "event" | "ping" | "pong" | "error";
  eventId?: string;
  title?: string;
  description?: string;
  location?: string;
  urgencyLevel?: "low" | "medium" | "high" | "critical";
  timestamp?: string;
  error?: {
    message: string;
  };
}

// 中间件配置
app.use(helmet()); // 安全头
app.use(
  cors({
    origin: process.env.FRONTEND_URL || "http://localhost:3000",
    credentials: true,
  })
); // 跨域
app.use(morgan("combined")); // 日志
app.use(express.json({ limit: "10mb" })); // JSON解析
app.use(express.urlencoded({ extended: true })); // URL编码

// API路由
app.use("/", apiRoutes);

// 健康检查
app.get("/health", (req: express.Request, res: express.Response) => {
  res.json({
    status: "OK",
    timestamp: new Date().toISOString(),
    uptime: process.uptime(),
  });
});

// WebSocket服务器 - 用于实时应急事件推送
const wss = new WebSocketServer({ port: 8080 });
const clients = new Set<WebSocket>();

console.log("🚀 WebSocket server started on port 8080");

wss.on("connection", (ws: WebSocket) => {
  console.log("🔗 New WebSocket connection");
  clients.add(ws);

  // 发送欢迎消息
  const welcomeMessage: EmergencyEvent = {
    type: "event",
    title: "Connected to Emergency System",
    timestamp: new Date().toISOString(),
  };
  ws.send(JSON.stringify(welcomeMessage));

  // 处理客户端消息
  ws.on("message", (data: Buffer) => {
    try {
      const message: EmergencyEvent = JSON.parse(data.toString());

      switch (message.type) {
        case "ping":
          const pongMessage: EmergencyEvent = {
            type: "pong",
            timestamp: new Date().toISOString(),
          };
          ws.send(JSON.stringify(pongMessage));
          break;

        default:
          const errorMessage: EmergencyEvent = {
            type: "error",
            error: {
              message: "Unknown message type",
            },
          };
          ws.send(JSON.stringify(errorMessage));
      }
    } catch (error: any) {
      const errorMessage: EmergencyEvent = {
        type: "error",
        error: {
          message: "Invalid JSON format",
        },
      };
      ws.send(JSON.stringify(errorMessage));
    }
  });

  // 处理连接断开
  ws.on("close", () => {
    console.log("❌ WebSocket connection closed");
    clients.delete(ws);
  });

  // 处理错误
  ws.on("error", (error: Error) => {
    console.error("WebSocket error:", error);
    clients.delete(ws);
  });
});

// 广播紧急事件到所有客户端
export const broadcastEmergencyEvent = (event: EmergencyEvent) => {
  clients.forEach((client) => {
    if (client.readyState === WebSocket.OPEN) {
      client.send(JSON.stringify(event));
    }
  });
};

// 启动服务器
const startServer = async (): Promise<void> => {
  try {
    // 初始化数据库连接池
    await createPool();

    // 启动HTTP服务器
    app.listen(PORT, () => {
      console.log(`🚀 Emergency Admin Server running on port ${PORT}`);
      console.log(`🔗 WebSocket: ws://localhost:8080`);
    });
  } catch (error) {
    console.error("❌ Server startup failed:", error);
    process.exit(1);
  }
};

startServer();
